<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>最佳拍档</title>
    <meta name="keywords" content="最佳拍档">
    <meta name="description" content="最佳拍档">
    <script th:src="@{/UEditor/ueditor.config.js}" src="/UEditor/ueditor.config.js"></script>
    <script th:src="@{/UEditor/ueditor.all.js}" src="/UEditor/ueditor.all.js"></script>
    <style>
        .right h2{
            margin: 10px 0;
        }
        .right li{
            margin-bottom: 10px;
        }
        #commodityDetail iframe{
            padding-left: 0px;
            padding-top: 0px;
            width: 800px;
        }
    </style>
</head>
<body>
<div class="right p20" style="margin-left: 200px;">
    <input type="hidden" id="userId" th:value="${loginUser.userid}">
    <input type="hidden" id="userRole" th:value="${userRole}">
    <div th:include="common/UserHeadDesc :: user_head_desc"></div>
    <div style="display: flex;justify-content: space-between">
        <div></div>
        <div style="display: flex;padding-right: 20px;">
            <div style="width: 250px;">
                <input type="text" name="keyword" id="keyword" required lay-verify="required" placeholder="请输入关键字" autocomplete="off" class="layui-input" onkeydown="keydownSearch()">
            </div>
            <div style="padding-left: 5px;">
                <button type="button" class="layui-btn" onclick="search()">搜索</button>
            </div>
        </div>
    </div>
    <div class="layui-row">
        <div class="layui-col-md12" style="padding-right: 20px">

            <table class="layui-table layui-form" lay-filter="EditListTable" id="EditListTable" lay-data="{id: 'tableid'}">
                <thead>
                <tr class="id36567">
                    <th lay-data="{checkbox:true}"></th>
                    <th lay-data="{field:'commodityStatus', align: 'center'}">商品状态</th>
                    <th lay-data="{field:'commodityNum', align: 'center'}">编号</th>
                    <th lay-data="{field:'shopName', align: 'center'}">1688店铺名称</th>
                    <th lay-data="{field:'commodityName', align: 'center'}">商品名称</th>
                    <th lay-data="{field:'commodityMap', align: 'center', templet: '#imgTemp', style: 'height:90px;'}">商品图</th>
                    <th lay-data="{field:'supplyPrice', align: 'center'}">供货价</th>
                    <th lay-data="{field:'floorPrice', align: 'center'}">控价</th>
                    <th lay-data="{field:'taobaoPrice', align: 'center'}">淘宝定价</th>
                    <th lay-data="{field:'channelPrice', align: 'center'}">渠道供货价</th>
                    <th lay-data="{fixed: 'right', toolbar: '#barDemo', width: 250, align: 'center'}">操作</th>
                </tr>
                </thead>
            </table>
            <script type="text/html" id="barDemo">
                {{# if(d.commodityStatus == '未上架淘宝'){ }}
                    <a class="layui-btn layui-btn-xs" lay-event="set_shelves_time_single" th:if="${userRole.indexOf('deptManage') != -1}">计划上架</a>
                {{# } }}
                {{# if(d.commodityStatus == '已安排上架'){ }}
                    <a class="layui-btn layui-btn-xs" lay-event="goods_on_shelves" th:if="${userRole.indexOf('taobaoManage') != -1}">上架商品</a>
                {{# } }}
                {{# if(d.signingStatus == 2 && d.commodityStatus == "未定价"){ }}
                    <a class="layui-btn layui-btn-xs" lay-event="set_price" th:if="${userRole.indexOf('priceClerk') != -1}">商品定价</a>
                {{# } }}
                <a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="commodity_details">商品详情</a>
                <a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="brand_details">品牌详情</a>
            </script>
        </div>
        <!-- 头部工具栏 -->
        <script type="text/html" id="toolbar">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-sm" lay-event="generatePDF"><i class="layui-icon">&#xe631;</i>渠道选品</button>
                <button class="layui-btn layui-btn-sm" lay-event="set_shelves_time" th:if="${userRole.indexOf('deptManage') != -1}"><i class="layui-icon">&#xe68d;</i>计划上架</button>
            </div>
        </script>
        <script type="text/html" id="imgTemp">
            <img src="{{d.commodityMap}}" style="width: 100px;height: 80px;" />
        </script>
    </div>

    <!--设置上架时间-->
    <div id="set_time_model" style="display: none;">
        <form class="layui-form" lay-filter="PriceForm" id="set_time_form" style="padding-right: 50px;padding-top: 40px;">
            <div class="layui-form-item">
                <label class="layui-form-label">上架时间</label>
                <div class="layui-input-block">
                    <input type="text" class="layui-input" name="planTime" required lay-verify="required" id="shelvesTimeid" placeholder="请选择上架时间" readonly>
                </div>
            </div>
        </form>
    </div>

    <!--淘宝运营上架商品-->
    <div id="goods_shelves_model" style="display: none;">
        <form class="layui-form" lay-filter="PriceForm" id="goods_shelves_form" style="padding-right: 50px;padding-top: 40px;">
            <div class="layui-form-item">
                <label class="layui-form-label">上架时间</label>
                <div class="layui-input-block">
                    <input type="text" class="layui-input" name="shelfTime" required lay-verify="required" id="shelvesTimeid" placeholder="请选择真实上架时间" readonly>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">退货地址</label>
                <div class="layui-input-block">
                    <input type="text" name="returnAddress" autocomplete="off" class="layui-input" placeholder="请填写退货地址" required lay-verify="required">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">商品链接</label>
                <div class="layui-input-block">
                    <input type="text" name="taobaoLink" autocomplete="off" class="layui-input" placeholder="请填写商品链接" required lay-verify="required">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">商品详情</label>
                <div class="layui-input-block" style="width: 800px;">
                    <textarea id="commodityDetail" name="text" ></textarea>
                </div>
            </div>
        </form>
    </div>

    <!--定价填写内容-->
    <div id="set_price_model" style="display: none;">
        <form class="layui-form" lay-filter="PriceForm" id="set_price_form" style="padding-right: 50px;padding-top: 40px;">
            <div class="layui-form-item">
                <label class="layui-form-label">淘宝定价</label>
                <div class="layui-input-block">
                    <input type="text" name="taobaoPrice" autocomplete="off" class="layui-input" placeholder="请填写淘宝定价" required lay-verify="number">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">渠道供货价</label>
                <div class="layui-input-block">
                    <input type="text" name="channelPrice" autocomplete="off" class="layui-input" placeholder="请填写渠道供货价" required lay-verify="number">
                </div>
            </div>
        </form>
    </div>

</div>
</body>

<script type="text/javascript">
    let ue;
    //加载列表的后端 url
    let getListUrl = '/commodity/list';
    //初始化导航栏选中
    window.onload=function(){
        let userId = $("#userId").val()
        initFormData(userId)
        if(document.getElementById('commodityDetail')!=null){
            ue = UE.getEditor('commodityDetail');
        }
        ue.ready(function() {
            ue.setHeight(400);
        })
        //固定导航栏
        let url = window.location.pathname;
        if(url=="/" || url=="/Admin"){

        }else{
            $('a[href="'+url+'"]').parent().addClass('layui-this');
            $('a[href="'+url+'"]').parent().parent().parent().addClass('layui-nav-itemed');
        }
    }

    function initFormData(userId){
        layui.use(['table', 'layer'], function () {//layui 模块引用，根据需要自行修改
            let layer = layui.layer, table = layui.table;
            //对于任意一个 table，按照官方的说法，有三种不同的初始化渲染方式，不多介绍，而这里使用的方式姑且看做第三种：转换静态表格 方式
            //转换静态表格方式，自然首先需要有一个已经存在的表格，然后再通过 js 方式转化为 Layui 表格
            //无论哪种方式的 Layui table 初始化自然需要配置项
            //通过转化的方式初始化 Layui table，配置项部分可以在 源table中，部分在js中，源 table 的源代码上文已经给出，下面给出一个示例的 js 中的配置项
            var tableOptions = {
                elem: '#EditListTable',
                url: getListUrl, //请求地址
                method: 'GET', //方式
                id: 'EditListTable', //生成 Layui table 的标识 id，必须提供，用于后文刷新操作，笔者该处出过问题
                page: true, //是否分页
                request: {
                    pageName: 'pageNum',
                    limitName: 'pageSize'
                },
                where: {}, //请求后端接口的条件，该处就是条件错误点，按照官方给出的代码示例，原先写成了 where: { key : { type: "all" } }，结果并不是我想的那样，如此写，key 将是后端的一个类作为参数，里面有 type 属性，如果误以为 key 是 Layui 提供的格式，那就大错特错了
                response: { //定义后端 json 格式，详细参见官方文档
                    statusName: 'code', //状态字段名称
                    statusCode: '200', //状态字段成功值
                    msgName: 'msg', //消息字段
                    countName: 'total', //总数字段
                    dataName: 'rows' //数据字段
                },
                limit: 10,//每页显示条数
                limits: [10,20,50,100,150,200,300],//可选择范围
                defaultToolbar: ['filter'],
                toolbar: '#toolbar'
            };
            // 表初始化
            var createTable = function () {
                table.init('EditListTable', tableOptions);// table lay-filter
            };

            // 表初始化
            createTable();

            //监听行工具事件
            table.on('tool(EditListTable)', function (obj) {
                var data = obj.data;
                if(obj.event === 'set_shelves_time_single'){//设置上架时间
                    let ids = [];
                    ids.push(data.commodityId);
                    set_plan_time(ids);
                }else if (obj.event === 'commodity_details') {
                    window.location.href = "http://" + window.location.host + "/Admin/Commodity/CommodityDetails?commodityId="+data.commodityId;
                }else if (obj.event === 'brand_details') {
                    window.location.href = "http://" + window.location.host + "/Admin/Brand/BrandDetailsReadonly?unid="+data.customerId;
                }else if (obj.event === 'goods_on_shelves'){
                    goods_on_shelves(data.commodityId);
                }else if (obj.event === 'set_price'){
                    set_price(data.commodityId);
                }
            });

            //头部工具栏按钮触发事件
            table.on('toolbar(EditListTable)', function(obj) {
                //获取选中行
                let toolbar = table.checkStatus(obj.config.id);
                switch (obj.event) {
                    case 'generatePDF':
                        if (toolbar.data.length > 0) {
                            let ids = [];
                            for (let i in toolbar.data){
                                ids.push(toolbar.data[i].commodityId);
                            }
                            $.ajax({
                                url: '/commodity/preview',
                                type: 'POST',
                                data: JSON.stringify(ids),
                                contentType: 'application/json',
                                dataType: 'json', // 用于设置响应体的类型 注意 跟 data 参数没关系！！！
                                success: function (res) {
                                    if(res.code == 200){
                                        layer.open({
                                            type: 1,
                                            area: ['500px', '800px'],
                                            content: '<embed src="'+res.msg+'" type="application/pdf" width="100%" height="100%">' //这里content是一个普通的String
                                        });
                                    }else {
                                        layer.msg(res.msg);
                                    }
                                }
                            });
                        }else{
                            layer.msg("请至少选择一项");
                        }
                    break;
                    case 'set_shelves_time':
                        if (toolbar.data.length > 0) {
                            let ids = [];
                            for (let i in toolbar.data){
                                if(toolbar.data[i].commodityStatus != "未上架淘宝"){
                                    layer.msg("只能选择状态为未上架淘宝的商品进行设置计划上架时间噢！");
                                    return;
                                }
                                ids.push(toolbar.data[i].commodityId);
                            }
                            set_plan_time(ids);
                        }else{
                            layer.msg("请至少选择一项");
                        }
                    break;
                }
            })

        });
    }

    //设置计划上架时间
    function set_plan_time(commodityIds){
        layui.use('layer', function(){
            let layer = layui.layer;
            layer.open({
                type: 1
                ,title: '设置上架时间'
                , content: $('#set_time_model')
                , area: 'auto'//定义宽和高
                , btnAlign: 'c' //按钮居中
                , shade: 0 //不显示遮罩
                ,btn: ['确定', '取消']
                , yes: function (index, layero) {
                    let planTime = $('input[name="planTime"]').val();
                    if(isNotNull(planTime)){
                        let data_arr = [];
                        for(let i in commodityIds){
                            let sub_data = {
                                commodityId: commodityIds[i],
                                planTime: planTime,
                            }
                            data_arr.push(sub_data);
                        }
                        $.ajax({
                            type:'PUT',
                            url:'/commodity/edit',
                            data: JSON.stringify(data_arr),
                            dataType:'json',
                            contentType: 'application/json; charset=UTF-8',
                            success:function(req){
                                $("#set_time_model").css("display","none");
                                layer.close(index);
                                layer.msg("已提交给淘宝运营进行上架，请耐心等候！");
                                // 重载表格数据
                                reloadTable();
                                return false;
                            },
                            error:function(e){
                                $("#set_time_model").css("display","none");
                                layer.close(index);
                                layer.msg("出错啦！");
                            }
                        })
                    }else{
                        layer.msg("请填写完整再进行提交噢！");
                    }
                }
                ,btn2: function(index, layero){
                    //按钮【按钮二】的回调
                    layer.closeAll();
                    $("#set_time_model").css("display","none");
                    //return false 开启该代码可禁止点击该按钮关闭
                }
                ,cancel: function(index, layero){
                    //右上角关闭回调
                    $("#set_time_model").css("display","none");
                    layer.closeAll();
                }
            });
        });
    }

    //上架商品
    function goods_on_shelves(commodityId){
        layui.use('layer', function() {
            let layer = layui.layer;
            layer.open({
                type: 1
                ,title: '上架商品'
                , content: $('#goods_shelves_model')
                , area: 'auto'//定义宽和高
                , btnAlign: 'c' //按钮居中
                , shade: 0 //不显示遮罩
                ,btn: ['确定', '取消']
                , yes: function (index, layero) {
                    let shelfTime = $('input[name="shelfTime"]').val();
                    let returnAddress = $('input[name="returnAddress"]').val();
                    let taobaoLink = $('input[name="taobaoLink"]').val();
                    let commodityDetail = ue.getContent();
                    if(isNotNull(shelfTime) && isNotNull(taobaoLink)){
                        let data_arr = [];
                        let sub_data = {
                            commodityId: commodityId,
                            shelfTime: shelfTime,
                            returnAddress: returnAddress,
                            taobaoLink: taobaoLink,
                            commodityDetail: commodityDetail
                        }
                        data_arr.push(sub_data);
                        $.ajax({
                            type:'PUT',
                            url:'/commodity/edit',
                            data: JSON.stringify(data_arr),
                            dataType:'json',
                            contentType: 'application/json; charset=UTF-8',
                            success:function(req){
                                $("#goods_shelves_model").css("display","none");
                                layer.close(index);
                                layer.msg("上架成功！");
                                // 重载表格数据
                                reloadTable();
                                return false;
                            },
                            error:function(e){
                                $("#goods_shelves_model").css("display","none");
                                layer.close(index);
                                layer.msg("出错啦！");
                            }
                        })
                    }else{
                        if(!isNotNull(shelfTime)){
                            layer.msg("请选择上架时间！");
                        }else if(!isNotNull(taobaoLink)){
                            layer.msg("请填写淘宝链接！");
                        }
                    }
                }
                ,btn2: function(index, layero){
                    //按钮【按钮二】的回调
                    $("#goods_shelves_model").css("display","none");
                    layer.closeAll();
                    //return false 开启该代码可禁止点击该按钮关闭
                }
                ,cancel: function(index, layero){
                    //右上角关闭回调
                    $("#goods_shelves_model").css("display","none");
                    layer.closeAll();
                }
            });
        })
    }

    //商品定价
    function set_price(commodityId){
        layui.use('layer', function() {
            let layer = layui.layer;
            //先清空表单数据
            $('input[name="cooperateGrade"]').val("");
            $('input[name="channelPrice"]').val("");
            layer.open({
                type: 1
                ,title: '商品定价'
                , content: $('#set_price_model')
                , area: 'auto'//定义宽和高
                , btnAlign: 'c' //按钮居中
                , shade: 0 //不显示遮罩
                ,btn: ['确定', '取消']
                , yes: function (index, layero) {
                    let taobaoPrice = $('input[name="taobaoPrice"]').val();
                    let channelPrice = $('input[name="channelPrice"]').val();
                    if(isNotNull(taobaoPrice) && isNotNull(channelPrice)){
                        let data_arr = [];
                        let sub_data = {
                            commodityId: commodityId,
                            taobaoPrice: taobaoPrice,
                            channelPrice: channelPrice
                        }
                        data_arr.push(sub_data);
                        $.ajax({
                            type:'PUT',
                            url:'/commodity/edit',
                            data: JSON.stringify(data_arr),
                            dataType:'json',
                            contentType: 'application/json; charset=UTF-8',
                            success:function(req){
                                $("#set_price_model").css("display","none");
                                layer.close(index);
                                layer.msg("商品已入库！");
                                // 重载表格数据
                                reloadTable();
                                return false;
                            },
                            error:function(e){
                                $("#set_price_model").css("display","none");
                                layer.close(index);
                                layer.msg("出错啦！");
                            }
                        })
                    }else{
                        layer.msg("请填写完整再进行提交噢！");
                    }
                }
                ,btn2: function(index, layero){
                    //按钮【按钮二】的回调
                    $("#set_price_model").css("display","none");
                    layer.close(index);
                }
                ,cancel: function(index, layero){
                    //右上角关闭回调
                    $("#set_price_model").css("display","none");
                    layer.close(index);
                }
            });
        })
    }

    //渲染日期控件
    layui.use('laydate', function(){
        let laydate = layui.laydate;
        laydate.render({
            elem: '#shelvesTimeid',
            trigger: 'click'
        });
    });

    //刷新表格数据
    function reloadTable(){
        layui.use('table', function() {
            let table = layui.table;
            table.reload("tableid", { //此处是上文提到的 初始化标识id
                url: getListUrl,
                where: {}
            });
        })
    }

    //搜索
    function search(){
        layui.use(['table', 'layer'], function () {//layui 模块引用，根据需要自行修改
            let layer = layui.layer, table = layui.table;
            table.reload('tableid', {
                where: {
                    searchStr:$("#keyword").val()
                }
                ,page: {
                    pageNum: 1 //重新从第 1 页开始
                }
            });
        })
    }

    //回车搜索
    function keydownSearch() {
        let event = window.event || arguments.callee.caller.arguments[0];
        if (event.keyCode == 13)
        {
            search();
        }
    }
    //获取地址栏参数
    function GetQueryString(name){
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if(r!=null)return  unescape(r[2]);
        return null;
    }

    /**
     * 判断值是否不为空
     * @param {Object} val
     */
    function isNotNull(val){
        if(val!=='undefined' && val!=="" && val!=null){
            return true
        }
        return false
    }


</script>

</html>